package org.swingannotations.impl;

import java.awt.Component;
import java.awt.Container;
import java.lang.reflect.Field;
import java.util.Iterator;

import org.swingannotations.JReference;

public class JReferenceProcessor {

	SwingContainerSearcher searcher = null;
	ComponentCatalog catalog = null;
	
	public JReferenceProcessor(SwingContainerSearcher searcher,ComponentCatalog catalog)
	{
		this.searcher  = searcher;
		this.catalog = catalog;
	}
	
	public void processAnnotations()
	{
		Iterator iterator = catalog.getControllerList().iterator();
		
		while (iterator.hasNext())
		{
			processController(iterator.next());
		}
	}
	
	
	public void processController(Object controller)
	{
		Field[] fields = controller.getClass().getDeclaredFields();
		for ( int i=0;i<fields.length;i++)
		{
			fields[i].isAnnotationPresent(JReference.class);
		}
	}
	
	
	public void processField(Object controller, Field field)
	{
		JReference referece = (JReference)field.getAnnotation(JReference.class);
		Class clazz = field.getDeclaringClass();
		
		
		Component component = searcher.findComponent(referece.name(),(Class<Component>)field.getDeclaringClass());
		if( component != null)
			injectComponent(controller, component,field);
	}
	
	protected void injectComponent(Object controller,Component component, Field field)
	{
		boolean securityChange = false;
		securityChange = !field.isAccessible();
		if( securityChange)
			field.setAccessible(true);
		try {
			field.set(controller, component);
		} catch (IllegalArgumentException e) {
			
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			
			e.printStackTrace();
		}
		finally
		{
			if (securityChange)
				field.setAccessible(false);
		}
		
		
	}
}
